package com.xc.gateway.filter;

import com.xc.gateway.config.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: 网关拦截器</p>
 * <P>创建人: 小程</p>
 * <P>创建人邮箱:779943476@qq.com</p>
 * <p>创建时间: 2019/07/12</p>
 *
 * @version v1.0
 */
@Slf4j
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

    @Autowired
    public Constants constants;

    /**
     * <p>功能描述: 拦截分配 </p>
     * <p>更新人: 小程</p>
     * <p>更新描述: 添加方法</p>
     * <p>更新人邮箱: 779943476@qq.com</p>
     * <p>更新时间: 2019/7/2</p>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put("startTime", System.currentTimeMillis());
        ServerHttpRequest request = exchange.getRequest();
        return chain.filter(exchange.mutate().request(request).build()).then(Mono.fromRunnable(() -> {
            log.info("请求地址:" + exchange.getRequest().getURI().getPath()
                    + ",请求方法:" + exchange.getRequest().getMethod()
                    + ",请求用时(毫秒):" + (System.currentTimeMillis() - (long) exchange.getAttributes().get("startTime")));
        }));
    }

    /**
     * <p>功能描述: 拦截器执行顺序越小越先执行 </p>
     * <p>更新人: 小程</p>
     * <p>更新描述: 添加方法</p>
     * <p>更新人邮箱: 779943476@qq.com</p>
     * <p>更新时间: 2019/7/2</p>
     *
     * @return 执行顺序值
     */
    @Override
    public int getOrder() {
        return -2;
    }
}
